@echo off

setlocal 
%~d0
cd "%~dp0"

REM --------- Variables ---------
Set APPCMD="%systemroot%\system32\inetsrv\APPCMD"
IF EXIST %WINDIR%\SysWow64 (
set powerShellDir=%WINDIR%\SysWow64\windowspowershell\v1.0
) ELSE (
set powerShellDir=%WINDIR%\system32\windowspowershell\v1.0
)
REM -----------------------------

ECHO.
ECHO ===============================
ECHO OData For TFS Demo Setup 
ECHO ===============================
ECHO.

pushd "%~dp0..\..\..\"

SET AspnetRegiisPath="C:\Windows\Microsoft.NET\Framework\v4.0.30319"
IF EXIST "C:\WINDOWS\Microsoft.NET\Framework64\" SET AspnetRegiisPath="C:\Windows\Microsoft.NET\Framework64\v4.0.30319"
@CALL %AspnetRegiisPath%\aspnet_regiis.exe -i

ECHO Unlocking IIS Authentication Module Sections...
%APPCMD% unlock config /section:windowsAuthentication
%APPCMD% unlock config /section:anonymousAuthentication

ECHO.
ECHO Setting up permissions in Program Data local folder...
CACLS "%programdata%\Microsoft\Team Foundation" /E /G "IIS_IUSRS":F /T /C
ICACLS "%programdata%\Microsoft\Team Foundation" /grant :r "IIS_IUSRS":F /T /Q /C

ECHO.
ECHO Setting up permissions in Web site folder...
CACLS "%CD%\code\ODataTFS.Web" /E /G "IIS_IUSRS":F /T /C
ICACLS "%CD%\code\ODataTFS.Web" /grant :r "IIS_IUSRS":F /T /Q /C

ECHO.
ECHO Exporting local certificate (127.0.0.1.cer)...

IF EXIST "%PROGRAMFILES%\Microsoft CAPICOM 2.1.0.2 SDK" (
    SET capicompath="%PROGRAMFILES%\Microsoft CAPICOM 2.1.0.2 SDK\Samples\vbs\cstore.vbs"
    SET cscript=%windir%\system32\cscript.exe
    %windir%\system32\regsvr32.exe /s "C:\Program Files\Microsoft CAPICOM 2.1.0.2 SDK\Lib\X86\capicom.dll"

)

IF EXIST "%PROGRAMFILES(x86)%\Microsoft CAPICOM 2.1.0.2 SDK" (
    SET capicompath="%PROGRAMFILES(x86)%\Microsoft CAPICOM 2.1.0.2 SDK\Samples\vbs\cstore.vbs"
    SET cscript=%windir%\syswow64\cscript.exe
    ECHO Setting up CAPICOM for 64 bits environment...
    copy /y "%PROGRAMFILES(x86)%\Microsoft CAPICOM 2.1.0.2 SDK\Lib\X86\capicom.dll" %windir%\syswow64
    %windir%\syswow64\regsvr32.exe /s %windir%\syswow64\capicom.dll
)

echo %CD%\setup\assets\127.0.0.1.cer

%cscript% /nologo %capicompath% export -l LM -s My -subject "127.0.0.1" -issuer "127.0.0.1" "%CD%\setup\assets\127.0.0.1.cer"

popd

ECHO.
ECHO ===============================
ECHO Setup finished successfully!
ECHO ===============================